<template>
  <div>
    <el-input
      v-model="filterText"
      prefix-icon="el-icon-search"
      placeholder="输入关键字进行过滤"/>

    <el-tree
      ref="tree"
      :data="data"
      :props="defaultProps"
      :check-strictly="true"
      :filter-node-method="filterNode"
      :expand-on-click-node="false"
      :default-checked-keys="checkedKeys"
      show-checkbox
      default-expand-all
      highlight-current
      node-key="id"
      class="filter-tree"
      @check-change="handleCheckChange"
    />
  </div>
</template>

<script>
import { serviceTree4All } from '@/api/admin'
export default {
  name: 'KjbServiceTreeSelect',
  props: {
    hasQd: {
      type: Boolean,
      default: true
    },
    onlyQd: {
      type: Boolean,
      default: false
    },
    checkedKeys: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      filterText: '',
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val)
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getData() {
      var root = [{
        id: 'TOP',
        label: '全部',
        children: [],
        disabled: true
      }]
      serviceTree4All(this.hasQd, this.onlyQd).then(res => {
        this.initTree(res.data)
        root[0].children = res.data
        this.data = root
      })
    },
    initTree(arr) {
      if (arr && arr.length) {
        console.log('arr', arr)
        for (let i = 0; i < arr.length; i++) {
          if (!arr[i].sysAreaCodes || arr[i].sysAreaCodes.indexOf(',') === -1) {
            arr[i].disabled = true
          }
          if (arr[i].children && arr[i].children.length) {
            this.initTree(arr[i].children)
          }
        }
      }
    },
    handleCheckChange() {
      this.$emit('handleCheckChange', this.$refs.tree.getCheckedNodes())
    }
  }
}
</script>
